package picturetaker.utility;

import java.io.File;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.naming.NamingException;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import picturetaker.domain.Camera;
import picturetaker.domain.CameraDomainMapper;
import picturetaker.persistence.JNDIFactory;

public class MyXMLReader implements ApplicationConstants {

	private static SAXReader parser = null;

	private static long modified = -1;

	private static Document doc = null;

	public static List<Camera> readConfiguration() {
		if (parser == null) {
			parser = new SAXReader();
		}

		try {
			File file = new File(JNDIFactory.getInstance().getEnvirontmentAsString("projectPath")
							   + JNDIFactory.getInstance().getEnvirontmentAsString("configPath")
							   + JNDIFactory.getInstance().getEnvirontmentAsString("defaultXML"));
			if (file.exists())
				return parse(file, false);
			else
				return null;
		} catch (NamingException e) {
			return null;
		}
	}

	private static List<Camera> parse(File file, boolean isDefault) {
		if (!isDefault)
			modified = file.lastModified();
		List<Camera> result = new ArrayList<Camera>();
		try {
			doc = parser.read(file);
			List list = doc.selectNodes(SELECT_NODES_CAMERA);
			result = mapObjects(list);
			return result;
		} catch (DocumentException e) {
			return result;
		}
	}

	private static List<Camera> mapObjects(List objects) {
		List<Camera> result = new ArrayList<Camera>();
		Iterator iter = objects.iterator();
		Element element = null;
		while (iter.hasNext()) {
			element = (Element) iter.next();
			try {
				result.add(CameraDomainMapper.mapCameraFromXMLElement(element));
			} catch (MalformedURLException e) {
			}
		}
		return result;
	}

	public static long readTimerConfiguration() {
		Long result = null;
		if (doc != null) {
			Element element = (Element) doc.selectObject(SELECT_NODE_TIMER);
			if(element != null)
				result = Long.valueOf(element.attribute(VALUE_ATTRIBUTE).getText());
		}
		return result == null ? -1 : result.longValue();

	}
}